package ce.com.newbluedemo.K6;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import ce.com.cenewbluesdk.CEBC;
import ce.com.cenewbluesdk.entity.k6.K6_GpsArgument;
import ce.com.cenewbluesdk.ota.ota_modea.OtaUtil;
import ce.com.cenewbluesdk.proxy.BleFactory;
import ce.com.cenewbluesdk.proxy.CEDevK6Proxy;
import ce.com.cenewbluesdk.uitl.ByteUtil;
import ce.com.cenewbluesdk.uitl.CRC16;
import ce.com.cenewbluesdk.uitl.TimeUtil;
import ce.com.newbluedemo.R;
import ce.com.newbluedemo.my.MyActivity;

/**
 * Created by YaoBingkun on 2017/1/4.
 */

public class ActivitySendGpsArgument extends MyActivity implements View.OnClickListener {
    private Handler gpsHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == CEBC.K6.DATA_TYPE_GPS_ARGUMENT) {
                switch (msg.arg1) {
                    case 0:
                        showToast("第" + sendIndex + "个数据包发送失败");
                        Log.d("正在发送", "第" + sendIndex + "个数据包发送失败");
                        mButtonRemote.setClickable(true);
                        mButtonLocal.setClickable(true);
                        mButtonLocal.setText("发送本地文件");
                        mButtonRemote.setText("发送网络文件");
                        sendIndex = -1;
                        break;
                    case 1:
                        sendIndex++;
                        byte[] nextItem = argument.getGpsArgHeadBytes();
                        if (nextItem != null) {
                            Log.d("正在发送", "第" + sendIndex + "个数据包");
                            mCEDevK6Proxy.getSendHelper().sendGpsArgument(nextItem);
                        } else {
                            showToast("所有数据包发送完成！");
                            mButtonRemote.setClickable(true);
                            mButtonLocal.setClickable(true);
                            mButtonLocal.setText("发送本地文件");
                            mButtonRemote.setText("发送网络文件");
                            sendIndex = -1;
                        }
                        break;
                    default:
                        break;
                }
            }

        }
    };


    private CEDevK6Proxy mCEDevK6Proxy;

    private int sendIndex = -1;

    private Button mButtonLocal, mButtonRemote;

    private K6_GpsArgument argument = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_k6_gps);
        mCEDevK6Proxy = BleFactory.getInstance().getK6Proxy();
        mCEDevK6Proxy.setHandler(gpsHandler);
        mButtonLocal = (Button) findViewById(R.id.btn_send_gps_file);
        mButtonLocal.setOnClickListener(this);
        mButtonRemote = (Button) findViewById(R.id.btn_send_gps_file_from_net);
        mButtonRemote.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (!mCEDevK6Proxy.isConnectOK()) {  //判断蓝牙连接状态
            showToast("未连接设备，请重试!");
            return;
        }
        if (sendIndex != -1) {
            showToast("正在发送数据中，请在发送完成后再试");
            return;
        }
        switch (v.getId()) {
            case R.id.btn_send_gps_file:
                try {
                    argument = new K6_GpsArgument(getRawFile(this, R.raw.current_2d), K6_GpsArgument.GPS_OFFLINE_TYPE, TimeUtil.now());
                    Log.e("CRC校验结果",OtaUtil.checkCrc16OK(argument.getCrc16(),
                            Arrays.copyOfRange(argument.getSendByte(),2,argument.getSendByte().length))?"正确":"错误" + "  " + CRC16.crc16( Arrays.copyOfRange(argument.getSendByte(),2,argument.getSendByte().length)));
                    byte[] data = argument.getGpsArgHeadBytes();
                    if (data != null) {
                        Log.e("CRC校验结果data",(argument.getCrc16() == ByteUtil.byte2ToInt(Arrays.copyOfRange(data,7,9)))?"正确":"错误" +
                                "  " + ByteUtil.byte2ToInt(Arrays.copyOfRange(data,7,9)));
                        mButtonLocal.setClickable(false);
                        mButtonLocal.setText("发送中...");
                        sendIndex = 0;
                        Log.d("正在发送", "第" + sendIndex + "个数据包");
                        mCEDevK6Proxy.getSendHelper().sendGpsArgument(data);
                    } else {
                        showToast("文件为空，请检查");
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.btn_send_gps_file_from_net:
                new DownloadTask().execute("http://online-live1.services.u-blox.com/GetOnlineData.ashx?toke" +
                        "n=JMUjM35wh0GmG8pmLGGCKw;gnss=gp" +
                        "s;datatype=eph,alm,aux;format=aid;");
                break;

        }

    }


    public class DownloadTask extends AsyncTask<String, Integer, K6_GpsArgument> {


        @Override
        protected K6_GpsArgument doInBackground(String... params) {
            byte[] data = getByteFileFromServer(params[0]);
            try {
                if (data != null) {
                    return new K6_GpsArgument(getByteFileFromServer(params[0]), K6_GpsArgument.GPS_ONLINE_TYPE, TimeUtil.now());
                } else {
                    return null;
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(K6_GpsArgument arg) {
            if (arg == null) {
                showToast("网络错误，请稍后重试");
                return;
            }
            argument = arg;
            Log.e("CRC校验结果",OtaUtil.checkCrc16OK(argument.getCrc16(),Arrays.copyOfRange(argument.getSendByte(),0,2))?"正确":"错误");
            byte[] data = arg.getGpsArgHeadBytes();
            if (data != null) {
                mButtonRemote.setClickable(false);
                mButtonRemote.setText("发送中...");
                sendIndex = 0;
                Log.d("正在发送", "第" + sendIndex + "个数据包");
                mCEDevK6Proxy.getSendHelper().sendGpsArgument(data);
            } else {
                showToast("文件为空，请检查");
            }
        }
    }

    private void showToast(String input) {
        Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
    }


    public static byte[] getByteFileFromServer(String addr) {
        try {
            URL url = new URL(addr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3000);
            int fileSize = conn.getContentLength();
            if (fileSize == -1)
                return null;
            byte[] result = new byte[fileSize];
            InputStream inputStream = conn.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                System.arraycopy(buffer, 0, result, total, len);
                total += len;
            }
//            File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
//            File file = new File(path,"mgaonline.ubx");
//            FileOutputStream outputStream = new FileOutputStream(file);
//            outputStream.write(result);
//            outputStream.flush();
//            outputStream.close();
            bufferedInputStream.close();
            inputStream.close();
            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getRawFile(Context context, int resId) {
        InputStream inputStream = context.getResources().openRawResource(resId);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int size = 0;
        byte[] buffer = new byte[1024];
        try {
            while ((size = inputStream.read(buffer, 0, 1024)) >= 0) {
                outputStream.write(buffer, 0, size);
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }


}
